package com.tuoyu.peopletest.adapter;


import android.content.Context;
import android.view.ViewGroup;


import com.tuoyu.peopletest.R;
import com.tuoyu.peopletest.holder.BaseRvHolder;
import com.tuoyu.peopletest.scinterface.OnItemDataListener;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * recycleview adapter 基础类
 */
public abstract class BaseRVAdapter<T> extends RecyclerView.Adapter<BaseRvHolder> {
    public String TAG = this.getClass().getSimpleName();
    public OnItemDataListener<T> mListener;
    public Context context;
    public List<T> mDatas;

    public BaseRVAdapter(Context context, List<T> datas) {
        this.context = context;
        mDatas = datas;
        if (mDatas == null) {
            throw new NullPointerException("BaseRVAdapter list为空");
        }
    }

    /**
     * 添加数据, 比如分页
     *
     * @param datas
     */
    public void addData(List<T> datas) {
        if (datas != null && datas.size() > 0) {
            datas.addAll(datas);
        }

    }

    /**
     * 更新数据
     *
     * @param datas
     */
    public void upData(List<T> datas) {
        mDatas.clear();
        if (datas != null && datas.size() > 0) {
            mDatas.addAll(datas);
        }
    }


    @NonNull
    @Override
    public BaseRvHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        BaseRvHolder holder = getHolder(viewType);
        holder.itemView.setOnClickListener((v) -> {
            if (mListener != null) {
                int position = (int) v.getTag(R.id.sc_id_recycleview_item);
                mListener.onItemData(mDatas.get(position), position);
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull BaseRvHolder holder, int position) {

        holder.setData(mDatas.get(position), position);
        holder.itemView.setTag(R.id.sc_id_recycleview_item, position);

    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    /**
     * 得到holder
     *
     * @return
     */
    public abstract BaseRvHolder getHolder(int viewType);

    /**
     * 此方法每次都掉用
     *
     * @param holder
     */
    public void getItemHolder(BaseRvHolder holder) {

    }

    public void setItemClickListener(OnItemDataListener<T> listener) {
        this.mListener = listener;
    }
}
